package com.mygdx.game;

import com.badlogic.gdx.*;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.tiled.TideMapLoader;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.net.HttpRequestBuilder;
import com.badlogic.gdx.net.HttpStatus;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.scenes.scene2d.actions.MoveToAction;
import com.badlogic.gdx.scenes.scene2d.ui.*;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.viewport.StretchViewport;


/**
 * Created by dell on 2018/1/30.
 */
public class TestMain extends ApplicationAdapter {

    // 视口世界的宽高统使用 480 * 800, 并统一使用伸展视口（StretchViewport）
    public static final float WORLD_WIDTH = 480;
    public static final float WORLD_HEIGHT = 800;

    private Stage stage;

    private Texture texture;

    private Image image; //图片控件

    private BitmapFont bitmapFont; //位图字体

    private Label label; //标签控件

    private Button button;


    private CheckBox checkBox;
    private Texture checkOnTexture;
    private Texture checkOffTexture;

    // 文本框的宽高
    public static final int TEXT_FIELD_WIDTH = 300;
    public static final int TEXT_FIELD_HEIGHT = 50;

    // 文本框（用户名）
    private TextField userNameText;
    // 文本框（密码）
    private TextField passwordText;
    //文本框背景纹理
    private Texture bgTexture;
    //文本框中的光标纹理
    private Texture cursorTexture;

    //纹理
    private Texture badlogicTexture;
    private Texture logoTexture;

    //演员
    private Image badlogicImage;
    private Image logoImage;

    //演员包围的矩形  ,,用于碰撞检测
    private final Rectangle badlogicRect = new Rectangle();
    private final Rectangle logoRect = new Rectangle();
    private Texture netTexture;


    @Override
    public void create() {
        super.create();
        Gdx.app.setLogLevel(Application.LOG_ERROR);
        // 使用伸展视口（StretchViewport）创建舞台
        stage = new Stage(new StretchViewport(WORLD_WIDTH,WORLD_HEIGHT));
       /* texture = new Texture(Gdx.files.internal("logo.png"));

        image = new Image(new TextureRegion(texture));


        image.setPosition(100,200);
        image.setScale(0.5f,1f);
        image.setRotation(-45);
        stage.addActor(image);

        bitmapFont = new BitmapFont(Gdx.files.internal("bitmapFont.fnt"));
        //要创建 Label 首先要创建一个 Label 的样式, 用于指明 Label 所使用的位图字体, 背景图片, 颜色等
        Label.LabelStyle labelStyle = new Label.LabelStyle();
        // 指定 Label 的背景, 可用纹理区域 textureRegion
        labelStyle.background = new TextureRegionDrawable(new TextureRegion(texture));
        labelStyle.font = bitmapFont; //指定 Label 所使用的位图字体
        labelStyle.fontColor = new Color(1,0,0,1);

        label = new Label("游戏开发框架 hello world \n哈哈 啊啊啊sdfdsf！",labelStyle);

        // 也可以通过方法设置或获取文本
        // label.setText("Hello");
        // String text = label.getText().toString();
        // // 设置 Label 的显示位置
        label.setPosition(50f,400f);
        // 可以通过设置字体的缩放比来控制字体显示的大小
        label.setFontScale(1.5f);

        stage.addActor(label);*/

        // 首先必须注册输入处理器（stage）, 将输入的处理设置给 舞台（Stage 实现了 InputProcessor 接口）
        // 这样舞台才能接收到输入事件, 分发给相应的演员 或 自己处理。
       Gdx.input.setInputProcessor(stage);
        //获得纹理图集
        TextureAtlas textureAtlas = new TextureAtlas(Gdx.files.internal("myatlas/aaaa.atlas"));
        TextureRegion upBtn = textureAtlas.findRegion("button",2);
        TextureRegion downBtn = textureAtlas.findRegion("button",1);
        Button.ButtonStyle buttonStyle = new Button.ButtonStyle();
        buttonStyle.up = new TextureRegionDrawable(upBtn);
        buttonStyle.down = new TextureRegionDrawable(downBtn);

        button = new Button(buttonStyle);
        button.addListener(new ClickListener(){
            @Override
            public void clicked(InputEvent event, float x, float y) {
                Gdx.app.error("tag","按钮被点击了");
            }
        });
        button.setPosition(0,100);
        stage.addActor(button);

        CheckBox.CheckBoxStyle checkBoxStyle = new CheckBox.CheckBoxStyle();
        checkOnTexture = new Texture(Gdx.files.internal("check_on.png"));
        checkOffTexture = new Texture(Gdx.files.internal("check_off.png"));
        checkBoxStyle.checkboxOn = new TextureRegionDrawable(new TextureRegion(checkOnTexture));
        checkBoxStyle.checkboxOff = new TextureRegionDrawable(new TextureRegion(checkOffTexture));
        checkBoxStyle.font = new BitmapFont(Gdx.files.internal("bitmapFont.fnt"));
//        checkBoxStyle.font = new BitmapFont();//使用默认的字体文件
        checkBoxStyle.fontColor = Color.RED;
        checkBox = new CheckBox("游戏框架",checkBoxStyle);
        checkBox.addListener(new ChangeListener() {
            @Override
            public void changed(ChangeEvent event, Actor actor) {
                Gdx.app.error("tag","复选框是否被选中："+checkBox.isChecked());
            }
        });
        stage.addActor(checkBox);

        //输入框
         /*
         * 第 1 步: 创建文本框背景纹理, 光标纹理, 以及创建位图字体（用于显示文本框中的文本）
         *
         * 为了方便演示, 这里创建纹理不再用图片来创建, 而是使用 Pixmap 来创建
         */

         //背景纹理
         bgTexture = createBgTexture();
         //光标纹理
         cursorTexture = createCursorTexture();
           /*
         * 第 2 步: 创建 TextFieldStyle
         */
        TextField.TextFieldStyle style = new TextField.TextFieldStyle();
        style.background = new TextureRegionDrawable(new TextureRegion(bgTexture));
        style.cursor = new TextureRegionDrawable(new TextureRegion(cursorTexture));
        bitmapFont = new BitmapFont(Gdx.files.internal("bitmapFont.fnt"));
        style.font = bitmapFont;
        // 设置文本框字体颜色为白色
        style.fontColor = new Color(0, 0, 0, 1);
         /*
         * 第 3 步: 创建 TextField
         */
         userNameText = new TextField("",style);
         passwordText = new TextField("",style);
         userNameText.setSize(TEXT_FIELD_WIDTH,TEXT_FIELD_HEIGHT);
         passwordText.setSize(TEXT_FIELD_WIDTH,TEXT_FIELD_HEIGHT);
        // 设置文本框的位置
        userNameText.setPosition(90, 500);
        passwordText.setPosition(90, 430);
        //设置文本中文字对其
        userNameText.setAlignment(Align.center);
        passwordText.setAlignment(Align.center);
        passwordText.setPasswordCharacter('*');
        passwordText.setPasswordMode(true);

        stage.addActor(userNameText);
        stage.addActor(passwordText);

        //碰撞检测
        badlogicTexture = new Texture(Gdx.files.internal("badlogic.jpg"));
        logoTexture = new Texture(Gdx.files.internal("logo.png"));
        badlogicImage = new Image(new TextureRegion(badlogicTexture));
        logoImage = new Image(new TextureRegion(logoTexture));
        badlogicImage.setPosition(0,300);
        logoImage.setPosition(0,0);

        stage.addActor(badlogicImage);
        stage.addActor(logoImage);

        MoveToAction moveToAction = Actions.moveTo(0, 600,5f);
        logoImage.addAction(moveToAction);

        //使用系统浏览器打开一个链接：
//        Gdx.net.openURI("http://www.baidu.com");;

        loadImageFromNet();
    }

    private void loadImageFromNet() {
//        String url = "https://libgdx.badlogicgames.com/img/logo.png";
        String url = "http://h.hiphotos.baidu.com/image/w%3D310/sign=8eaa413779ec54e741ec1c1f89399bfd/9d82d158ccbf6c812f9fe0e1be3eb13533fa400b.jpg";
        //创建请求构造器
        HttpRequestBuilder requestBuilder = new HttpRequestBuilder();
        Net.HttpRequest httpRequest = requestBuilder.newRequest().method(Net.HttpMethods.GET).url(url).build();
        Gdx.net.sendHttpRequest(httpRequest, new Net.HttpResponseListener() {
            @Override
            public void handleHttpResponse(Net.HttpResponse httpResponse) {
                HttpStatus status = httpResponse.getStatus();
                if (status.getStatusCode()==200) {
                    // 以字节数组的方式获取响应内容
                    final byte[] result = httpResponse.getResult();
                    // 还可以以流或字符串的方式获取
                    // httpResponse.getResultAsStream();
                    // httpResponse.getResultAsString();
                       /*
                     * 在响应回调中属于其他线程, 获取到响应结果后需要
                     * 提交到 渲染线程（create 和 render 方法执行所在线程） 处理。
                     */
                       Gdx.app.postRunnable(new Runnable() {
                           @Override
                           public void run() {
                               Pixmap pixmap = new Pixmap(result, 0, result.length);
                               netTexture = new Texture(pixmap);
                               Image image = new Image(new TextureRegion(netTexture));
                               pixmap.dispose();
                               image.setPosition(200,0);
                               stage.addActor(image);
                           }
                       });
                }else{
                    Gdx.app.error("tag","请求失败：错误码："+status.getStatusCode());
                }
            }

            @Override
            public void failed(Throwable t) {
                Gdx.app.error("tag","请求失败",t);
            }

            @Override
            public void cancelled() {
                Gdx.app.error("tag","请求取消");
            }
        });
    }

    private Texture createCursorTexture() {
        Pixmap pixmap = new Pixmap(1,TEXT_FIELD_HEIGHT-4,Pixmap.Format.RGBA8888);
        pixmap.setColor(1,0,0,1);
        pixmap.fill(); //填充
        Texture texture = new Texture(pixmap);
        pixmap.dispose();
        return texture;
    }

    /**
     * 创建文本框的背景纹理
     */
    private Texture createBgTexture() {
        Pixmap pixmap = new Pixmap(TEXT_FIELD_WIDTH,TEXT_FIELD_HEIGHT,Pixmap.Format.RGBA8888);
        pixmap.setColor(1,0,0,1);
        pixmap.drawRectangle(0,0,pixmap.getWidth(),pixmap.getHeight());
        Texture texture = new Texture(pixmap);
        pixmap.dispose();
        return texture;
    }

    @Override
    public void render() {
        super.render();
        Gdx.gl.glClearColor(1,1,1,1);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

        if (Gdx.input.isKeyJustPressed(Input.Keys.ENTER)) //点击了回车
        {
            Gdx.app.error("tag","账号："+userNameText.getText());
            Gdx.app.error("tag","密码："+passwordText.getText());
        }

        stage.act();

        //碰撞检测
        checkCollision();

        stage.draw();


     }

    /**
     * 碰撞检测
     */
    private void checkCollision() {
        /*
         * 获取演员的包围矩形
         *
         * 注意: 如果对演员进行了缩放旋转等变换, 需要获取的是变换后视觉上的包围矩形,
         * 后续的引擎封装中将详细介绍。
         */

        badlogicRect.set(badlogicImage.getX(),badlogicImage.getY(),badlogicImage.getWidth(),badlogicImage.getHeight());
        logoRect.set(logoImage.getX(),logoImage.getY(),logoImage.getWidth(),logoImage.getHeight());

        //  判断两个演员是否碰撞, 如果碰撞, 则将 badlogicActor 设置为半透明
        if (badlogicRect.overlaps(logoRect))
        {
            badlogicImage.getColor().a = 0.5f;
        }else{
            badlogicImage.getColor().a = 1f;
        }
    }

    @Override
    public void dispose() {
        super.dispose();
        if (stage!=null)
        {
            stage.dispose();
        }
        if (texture!=null)
        {
            texture.dispose();
        }
        if (checkOnTexture!=null)
        {
            checkOnTexture.dispose();
        }
        if (checkOffTexture!=null)
        {
            checkOffTexture.dispose();
        }
        if (bgTexture!=null)
        {
            bgTexture.dispose();
        }
        if (cursorTexture!=null)
        {
            cursorTexture.dispose();
        }
        if (netTexture!=null)
        {
            netTexture.dispose();
        }
    }
}
